﻿define(["moment", 'jqplot-donutRenderer', "module/moduleA/program/B01/custom_layout/default-config.js", 'xlsx'], function (moment) {
    return ["$scope", "$filter", "$stateParams", "config", "MMWService", "$calculater", "$mdDialog", "$state", '$log', '$timeout','$interval',
        function ($scope, $filter, $stateParams, config, $MMWService, $calculater, $mdDialog, $state, $log, $timeout,$interval) {
            $scope.init = function () {
                $scope.wo_no = '';
                $scope.mode = 'init';
                $scope.columnInfo = { 
                    name: $filter('translate')('SLI03.selectColumns.AndonTime'), 
                    code: 'tsesl.AndonTime'
                };
                $scope.typeInfo = { name: $filter('translate')('common.report.condition.equal'), code: '0' };
                $scope.columnValue = '';
                $scope.conditionList = [];
                $scope.andonDataList = [];
                $scope.andonDataList_temp = [];
                $scope.andonDetailDataList = [];
                $scope.codeList = [
                    { name: $filter('translate')('SLI03.selectColumns.AndonTime'), code: 'tsesl.AndonTime' },
                    { name: $filter('translate')('SLI03.selectColumns.SLightTypeNo'), code: 'tsesl.SLightTypeNo' },
                    { name: $filter('translate')('SLI03.selectColumns.SLightTypeName'), code: 'tstb.SLightTypeName' },
                    { name: $filter('translate')('SLI03.selectColumns.EquipmentNo'), code: 'tsesl.EquipmentNo' },
                    { name: $filter('translate')('SLI03.selectColumns.AreaNo'), code: 'tsesl.AreaNo' },
                    { name: $filter('translate')('SLI03.selectColumns.BASEAREANO'), code: 'tsaem.BASEAREANO' },
                    { name: $filter('translate')('SLI03.selectColumns.SLightReasonNo'), code: 'tsesl.SLightReasonNo' },
                    { name: $filter('translate')('SLI03.selectColumns.EQUIPMENTTYPE'), code: 'teqb.EQUIPMENTTYPE' },
                    { name: $filter('translate')('SLI03.selectColumns.Finisher'), code: 'tsesl.Finisher' },
                    { name: $filter('translate')('SLI03.selectColumns.ResponseLevel'), code: 'tsesl.ResponseLevel' }
                ];
                $scope.modeList = [
                    { name: $filter('translate')('common.report.condition.equal'), code: '0' },
                    { name: $filter('translate')('common.report.condition.nequal'), code: '1' },
                    { name: $filter('translate')('common.report.condition.contain'), code: '2' },
                    { name: $filter('translate')('common.report.condition.ncontain'), code: '3' },
                    { name: $filter('translate')('common.report.condition.exceed-equal'), code: '4' },
                    { name: $filter('translate')('common.report.condition.less-equal'), code: '5' },
                    { name: $filter('translate')('common.report.condition.exceed'), code: '6' },
                    { name: $filter('translate')('common.report.condition.less'), code: '7' }
                ];
                $scope.queryMode = 'list';
                $scope.showFlag = '0';
                $scope.select_tab = '0';
                $scope.changeDate($scope.columnInfo,3);
                // $scope.getEchars();
            };

            // 设定查询字段
            $scope.loadCodeList = function () {
                LoadCodeList();
            };

            // 打开查询字段下拉选择
            function LoadCodeList() {
                $scope.$root.showSelect({
                    title: $filter('translate')('common.report.condition_fields'),
                    label: 'name',
                    code: 'code',
                    selectCode: '',
                    list: $scope.codeList,
                    confirm: function (selectItem, dialog) {
                        $scope.columnInfo.name = selectItem.name;
                        $scope.columnInfo.code = selectItem.code;
                        if ($scope.columnInfo.code == 'tsesl.AndonTime') {
                            $scope.changeDate($scope.columnInfo, 3);
                        }
                        $scope.columnValue = '';
                        dialog.hide();
                    }
                });
            };

            // 设定条件类型
            $scope.loadTypeList = function (item) {
                loadTypeList();
            };

            // 打开条件类型下拉选择
            function loadTypeList() {
                $scope.$root.showSelect({
                    title: $filter('translate')('common.condition_title'),
                    label: 'name',
                    code: 'code',
                    selectCode: $scope.columnInfo.code,
                    list: $scope.modeList,
                    confirm: function (selectItem, dialog) {
                        $scope.typeInfo.name = selectItem.name;
                        $scope.typeInfo.code = selectItem.code;
                        dialog.hide();
                    }
                });
            };

            // 添加查询条件
            $scope.addCondition = function (type) {
                if ($scope.columnInfo.code != 'tsesl.AndonTime') {
                    if ($scope.columnInfo.name != null && $scope.columnInfo.name != '' && $scope.columnValue != null && $scope.columnValue != '') {
                        let conditionItem = {
                            columnName: $scope.columnInfo.name,
                            columnCode: $scope.columnInfo.code,
                            columnValue: ($scope.typeInfo.code != '2' && $scope.typeInfo.code != '3') ? $scope.columnValue : '%' + $scope.columnValue + '%',
                            conditionName: $scope.typeInfo.name,
                            conditionCode: $scope.typeInfo.code,
                            desc: $scope.columnInfo.name + ' ' + $scope.typeInfo.name + ' ' + $scope.columnValue
                        }
                        $scope.conditionList.push(conditionItem);
                        $scope.columnValue = '';
                    } else {
                        if(type == 0){
                            $scope.$root.showAlert($filter('translate')('C00.msg.condition_empty'));
                        }
                    }
                } else {
                    if ($scope.columnInfo.name != null && $scope.columnInfo.name != '' &&
                        (($scope.columnInfo.value_s != null && $scope.columnInfo.value_s != '') && ($scope.columnInfo.value_e != null && $scope.columnInfo.value_e != ''))) {
                        let conditionItem = {
                            columnName: $scope.columnInfo.name,
                            columnCode: $scope.columnInfo.code,
                            columnValue: $scope.columnInfo.value,
                            conditionName: $scope.typeInfo.name,
                            conditionCode: $scope.typeInfo.code,
                            timeRangeStart: moment($scope.columnInfo.value_s).format('YYYY-MM-DD') + ' 00:00:00',
                            timeRangeEnd: moment($scope.columnInfo.value_e).format('YYYY-MM-DD') + ' 23:59:59',
                            desc: $scope.columnInfo.name + ' ' + moment($scope.columnInfo.value_s).format('YYYY/MM/DD') + '~ ' + moment($scope.columnInfo.value_e).format('YYYY/MM/DD')
                        }
                        if($filter('filter')($scope.conditionList, {desc:conditionItem.desc}).length == 0){
                            $scope.conditionList.push(conditionItem);
                        }
                    } else {
                        if(type == 0){
                            $scope.$root.showAlert($filter('translate')('C00.msg.condition_empty'));
                        }
                    }
                }
            };

            // 点击查询条件
            $scope.selectCondition = function (index, item) {
                $log.log("==>点击查询条件");
                $scope.conditionList.splice(index, 1);
            };

            // 移除查询条件
            $scope.removeCondition = function (event, index) {
                $log.log("==>点击移除查询条件");
                $scope.conditionList.splice(index, 1);
                if($scope.conditionList.length == 0){
                    GetDefaultCondition($scope.codeList);
                    $scope.isClose = false;
                }
            };

            // 日期类型初始化
            function GetDefaultCondition(newVals){
                //20181121 modify bu Dustdusk for M#: 沒有設定必填條件，則抓第一筆當預設條件
                var item = angular.merge({}, newVals[0]);
                //20180927 modify by Dustdusk for 選完欄位後增加預設值
                if(item.code == 'tsesl.AndonTime'){
                    $scope.changeDate(item, 3);
                }
                $scope.columnInfo = item;
            }

            // 搜索
            $scope.search = function () {
                // 20210107 add FOR #80112
                $scope.addCondition(1);
                if($scope.conditionList == 0){
                    $scope.$root.showConfirm($filter('translate')('common.msg.no_report_condition_confirm'), 
                        function(dialog){
                            dialog.hide();
                            search();
                    });
                }else{
                    search();
                }
            };

            function search() {
                $scope.andonDataList = [];
                $scope.andonDataList_temp = [];
                let content = {
                    conditionList: []
                };
                if ($scope.conditionList.length > 0) {
                    let conditionList_temp = [];
                    $scope.conditionList.forEach(function (item, index, array) {
                        if(item.columnCode == 'tsesl.AndonTime'){
                            // 开始时间
                            let conditionItem = {
                                column_name: item.columnCode, // 列名
                                merge_condition_model: "AND", // 查询条件方式
                                query_mode: '4',
                                value: item.timeRangeStart,
                            };
                            conditionList_temp.push(conditionItem);

                            let conditionItem1 = {
                                column_name: item.columnCode, // 列名
                                merge_condition_model: "AND", // 查询条件方式
                                query_mode: '5',
                                value: item.timeRangeEnd,
                            };
                            conditionList_temp.push(conditionItem1);
                        }else{
                            let conditionItem = {
                                column_name: item.columnCode, // 列名
                                merge_condition_model: "AND", // 查询条件方式
                                query_mode: item.conditionCode, // 查詢條件代號	
                                value: item.columnValue,
                            };
                            conditionList_temp.push(conditionItem);
                        }
                        $scope.isClose = true;
                    })
                    content.conditionList = conditionList_temp;
                }

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SLI.slight_analysis_data_get',
                    content: content,
                    success: function (data) {
                        $scope.andonDataList = data.slightAnalysisList;
                        $scope.andonDataList_temp = data.slightAnalysisList;
                        $scope.getEchars();
                        if($scope.andonDataList.length > 0){
                            $scope.getAndonDetailInfo($scope.andonDataList[0]);
                        }else{
                            $scope.andonDetailDataList = [];
                        }
                    }
                });
            }

            $scope.getAndonDetailInfo = function (item) {
                getAndonDetailInfo(item);
            }

            // 获取安灯明细列表
            function getAndonDetailInfo(item) {
                $scope.andonDetailDataList = [];
                let content = {
                    slightTypeNo: item.SLightTypeNo,
                    slightReasonNo: item.SLightReasonNo
                }
                var has_time_condition = $filter('filter')($scope.conditionList,{columnCode:'tsesl.AndonTime'});
                if(has_time_condition && has_time_condition.length > 0)
                {
                    content.parnt_slight_start_time = has_time_condition[0].timeRangeStart;
                    content.parnt_slight_end_time = has_time_condition[0].timeRangeEnd;
                }
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SLI.slight_analysis_detail_data_get',
                    content: content,
                    success: function (data) {
                        $scope.andonDetailDataList = data.slightDetailList;
                        $scope.andonDetailDataList.forEach(itemData=>{
                            if(itemData.Grade){
                                if(itemData.Grade == 1){
                                    itemData.Grade = '普通';
                                }else if(itemData.Grade == 2){
                                    itemData.Grade = '中等';
                                }else if(itemData.Grade == 3){
                                    itemData.Grade = '緊急';
                                }
                            }
                        });
                    }
                });
            }

            // 汇出按钮（前端导出）
            $scope.export = function () {
                console.log("========汇出（导出）数据========")
                let listData = [];
                let detailListData = [];
                if (!$scope.andonDataList) {
                    $scope.$root.showAlert($filter('translate')('SLI01.msg.no_data'));
                    return;
                }
                let colorMap = {
                    '#68BD84': $filter('translate')('SLI01.color_list.green'), // 绿色
                    '#FFA500': $filter('translate')('SLI01.color_list.yellow'), // 黄色
                    '#db4d3e': $filter('translate')('SLI01.color_list.red')// 红色
                }
                var list_temp = $scope.andonDataList_temp;
                for (var i = 0; i < list_temp.length; i++) {
                    let itemData = list_temp[i];
                    itemData.EquipmentColourStr = colorMap[itemData.EquipmentColour];
                    itemData.QualityColourStr = colorMap[itemData.QualityColour];
                    itemData.MaterialColourStr = colorMap[itemData.MaterialColour];
                    itemData.ProdColourStr = colorMap[itemData.ProdColour];
                    let list = {
                        安灯分类: "",
                        安灯分类名称: "",
                        安灯原因编号: "",
                        安灯次数: "",
                        安灯时长: ""
                    };
                    list.安灯分类 = itemData.SLightTypeNo;
                    list.安灯分类名称 = itemData.SLightTypeName;
                    list.安灯原因编号 = itemData.SLightReasonNo;
                    list.安灯次数 = itemData.AndonNum;
                    list.安灯时长 = itemData.AllProcessTime;
                    listData.push(list);
                }

                let andonDetailDataList_temp = $scope.andonDetailDataList;
                if (andonDetailDataList_temp.length > 0) {
                    for (var i = 0; i < andonDetailDataList_temp.length; i++) {
                        let itemData = andonDetailDataList_temp[i];
                        let list = {
                            安灯分类: "",
                            安灯分类名称: "",
                            安灯原因: "",
                            安灯原因编号: "",
                            设备编号: "",
                            设备名称: "",
                            设备类别: "",
                            区域编号: "",
                            基底编号: "",
                            生产批号: "",
                            作业站编号: "",
                            物料编号: "",
                            描述: "",
                            响应等级: "",
                            紧急程度: "",
                            安灯时间: "",
                            安灯用户: "",
                            接受时间: "",
                            接受用户: "",
                            开始处理时间: "",
                            开始处理用户: "",
                            处理结束时间: "",
                            处理结束用户: "",
                            安灯结束确认时间: "",
                            确认用户: "",
                            安灯时长: "",
                            处理对策: "",
                            处理对策名称: "",
                            处理人评分: "",
                        };
                        list.安灯分类 = itemData.SLightTypeNo;
                        list.安灯分类名称 = itemData.SLightTypeName;
                        list.安灯原因 = itemData.SLightReasonNo;
                        list.安灯原因编号 = itemData.REASONNAME;
                        list.设备编号 = itemData.EquipmentNo;
                        list.设备名称 = itemData.EquipmentName;
                        list.设备类别 = itemData.EQUIPMENTTYPE;
                        list.区域编号 = itemData.AreaNo;
                        list.基底编号 = itemData.BASEAREANO;
                        list.生产批号 = itemData.LotNo;
                        list.作业站编号 = itemData.OPNo;
                        list.物料编号 = itemData.MaterialNo;
                        list.描述 = itemData.Description;
                        list.响应等级 = itemData.ResponseLevel;
                        list.紧急程度 = itemData.Grade;
                        list.安灯时间 = itemData.AndonTime;
                        list.安灯用户 = itemData.Andoner;
                        list.接受时间 = itemData.ReceiveTime;
                        list.接受用户 = itemData.Receiver;
                        list.开始处理时间 = itemData.StartTime;
                        list.开始处理用户 = itemData.Starter;
                        list.处理结束时间 = itemData.FinishTime;
                        list.处理结束用户 = itemData.Finisher;
                        list.安灯结束确认时间 = itemData.ConfromTime;
                        list.确认用户 = itemData.Confromer;
                        list.安灯时长 = itemData.ProcessTime;
                        list.处理对策 = itemData.Measure;
                        list.处理对策名称 = itemData.SLightMeasureName;
                        list.处理人评分 = itemData.Evaluate;
                        detailListData.push(list);
                    }
                }

                if (listData.length != 0) {
                    /* generate a worksheet */
                    let list_ws = XLSX.utils.json_to_sheet(listData);
                    /* add to workbook */
                    let wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, list_ws, $filter('translate')('SLI03.excel_sheet_names.name0'));
                    if (detailListData.length > 0) {
                        let detail_list_ws = XLSX.utils.json_to_sheet(detailListData);
                        XLSX.utils.book_append_sheet(wb, detail_list_ws, $filter('translate')('SLI03.excel_sheet_names.name1'));
                    }
                    /* write workbook and force a download */
                    var timestamp = $scope.formatDate(new Date());
                    var tittle = $filter('translate')('SLI03.excel_names.name0') + timestamp + ".xlsx";
                    var o;
                    const xlsxDataStr =  XLSX.writeFile(wb, tittle)
                    console.log(xlsxDataStr)
                    if(xlsxDataStr.length > 0){
                        $scope.$root.showToast($filter('translate')('SLI03.msg.print_success'));
                    }
                }
                else {
                    $scope.$root.showAlert($filter('translate')('SLI01.msg.no_data'));
                    return;
                }
            };

            $scope.formatDate = function (date) {
                let year = date.getFullYear();
                let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
                let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
                let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
                let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
                let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return year  + month  + day +  hours  + minutes + seconds;	// 返回格式化后的日期
            };

            // 打开安灯信息详细页面
            $scope.toAndonDetail = function (id) {
                console.log("==>toAndonDetail:" + id);
                $mdDialog.serviceDialog('AndonDetailService', {
                    id: id,
                    callback: function () {
                        dialog.beforeShown();
                    }
                });
            }

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            // 取消
            $scope.cancel = function () {
                $scope.mode = 'init';
                document.getElementById('kmi-pdf-panel').src = '';
                $scope.printList = [];
            };

            // 图标加载
            $scope.getEchars = function () {
                // 20210126 add FOR #80112
                $scope.clearEacharts();
                $timeout(function(){
                    // 分类分组
                    var list = $scope.arryGroupMatch($scope.andonDataList);
                    console.log(list);
    
                    var arr1 = [];
                    var arr2 = [];
                    var arr3 = [];
                    var arr4 = [];
                    list.forEach(e => {
                        var temp1 = [];
                        var temp3 = [];
                        e.data.map(r=> {
                            var temp = [];
                            temp[0] = e.SLightTypeName + '-' + r.SLightReasonNo;
                            temp[1] = Number(r.AndonNum);
                            arr1.push(temp);
                        })
    
                        e.data.map(r=> {
                            var temp4 = [];
                            temp4[0] = e.SLightTypeName + '-' + r.SLightReasonNo;
                            temp4[1] = Number(r.AllProcessTime);
                            arr4.push(temp4);
                        })
    
                        temp1[0] = e.SLightTypeNo;
                        var num1 = 0
                        e.data.map(r=> {
                            num1 += Number(r.AndonNum);
                        })
                        temp1[1] = num1;
                        arr2.push(temp1)
    
                        temp3[0] = e.SLightTypeNo;
                        var num3 = 0
                        e.data.map(r=> {
                            num3 += Number(r.AllProcessTime);
                        })
                        temp3[1] = num3;
                        arr3.push(temp3);
                    })   
                    
                    if(arr1.length > 0 && arr2.length > 0){
                        $.jqplot('kmi-chart1', [arr1, arr2], {
                            seriesDefaults: {
                                // make this a donut chart.
                                // 设置绘制一个环形图
                                renderer: $.jqplot.DonutRenderer,
                                rendererOptions: {
                                    // Donut's can be cut into slices like pies.
                                    // 环块之间的距离为3px
                                    sliceMargin: 3,
                                    // Pies and donuts can start at any arbitrary angle.
                                    // 起始位置为-90度，x轴正方向为0度
                                    startAngle: -90,
                                    showDataLabels: true,
                                    // By default, data labels show the percentage of the donut/pie.
                                    // You can show the data 'value' or data 'label' instead.
                                    // 可以设置在环块上显示的是数值还是标签
                                    dataLabels: 'value'
                                }
                            },
                            title:{ // 标题属性
                                text:$filter('translate')('SLI03.chart_title_1'), // 标题文本
                                show:true, // 是否阴影
                                fontFamily:'微软雅黑', // 标题字体 
                                fontSize:14, // 标题字体大小
                                textAlign:'center', // 标题对齐方式
                                textColor:'black', // 标题颜色（也可以写作属性color）
                                escapeHtml:false // 是否转义HTML字符，值为false时，可以在text属性中使用HTML代码
                            },
                            legend:{        // 图例属性
                                show:true,
                                placement: 'insideGrid' // 设置图例位于图表外部
                            }
                        });
                    }
    
                    if(arr3.length > 0 && arr4.length > 0){
                        $.jqplot('kmi-chart2', [arr4, arr3], {
                            seriesDefaults: {
                                // make this a donut chart.
                                // 设置绘制一个环形图
                                renderer: $.jqplot.DonutRenderer,
                                rendererOptions: {
                                    // Donut's can be cut into slices like pies.
                                    // 环块之间的距离为3px
                                    sliceMargin: 3,
                                    // Pies and donuts can start at any arbitrary angle.
                                    // 起始位置为-90度，x轴正方向为0度
                                    startAngle: -90,
                                    showDataLabels: true,
                                    // By default, data labels show the percentage of the donut/pie.
                                    // You can show the data 'value' or data 'label' instead.
                                    // 可以设置在环块上显示的是数值还是标签
                                    dataLabels: 'value'
                                }
                            },
                            title:{ // 标题属性
                                text:$filter('translate')('SLI03.chart_title_2'), // 标题文本
                                show:true, // 是否阴影
                                fontFamily:'微软雅黑', // 标题字体 
                                fontSize: 14, // 标题字体大小
                                textAlign:'center', // 标题对齐方式
                                textColor:'black', // 标题颜色（也可以写作属性color）
                                escapeHtml:false // 是否转义HTML字符，值为false时，可以在text属性中使用HTML代码
                            },
                            legend:{        // 图例属性
                                show:true,
                                placement: 'insideGrid' // 设置图例位于图表外部
                            }
                        });
                    }
                },1000);
            }

            // 20210126 add FOR #80112
            $scope.clearEacharts = function() {
                document.getElementById("kmi-chart1").innerHTML = '';
                document.getElementById("kmi-chart2").innerHTML = '';
            }

            $scope.arryGroupMatch = function(arr){
                var map = {}
                var dest = []
                for (var i = 0; i < arr.length; i++) {
                  var ai = arr[i]
                  if (!map[ai.SLightTypeNo]) {
                    dest.push({
                      SLightTypeNo: ai.SLightTypeNo,
                      SLightTypeName:ai.SLightTypeName,
                      data: [ai]
                    })
                    map[ai.SLightTypeNo] = ai
                  } else {
                    for (var j = 0; j < dest.length; j++) {
                      var dj = dest[j]
                      if (dj.SLightTypeNo === ai.SLightTypeNo) {
                        dj.data.push(ai)
                        break
                      }
                    }
                  }
                }
                return dest
            }

            $scope.changeView = function () {
                if ($scope.queryMode == 'list') {
                    $scope.queryMode = 'chart';
                    $scope.getEchars();
                } else {
                    $scope.queryMode = 'list';
                }
            };

            $scope.changeDate = function (item, date) {
                item.value_s = moment(new Date()).subtract(date, 'days').toDate();
                item.value_e = new Date();
                item.date_type = date;
            };

        }];
});
